import 'package:flutter/material.dart';
import 'package:jd_flutter/base/foundation/flutter_extension.dart';
import 'package:jd_flutter/base/router/navigator_util.dart';

import '../../foundation/jd_device.dart';
import '../../router/router_util.dart';
import '../image/jd_network_image.dart';

enum PageCloseButtonType { arrowBlack, arrowWhite, closeWhite, closeBlack }

double get kPreferredHeight => 44.dp;

typedef PopExtraParams = Map<String, dynamic> Function();

class BackButtonWrap extends StatelessWidget {
  // 是否是叉号样式
  final VoidCallback? callBack;
  final PageCloseButtonType backButtonType;

  const BackButtonWrap(
      {super.key,
      this.backButtonType = PageCloseButtonType.arrowBlack,
      this.callBack});

  @override
  Widget build(BuildContext context) {
    String backPic = 'assets/images/back.png';
    if (backButtonType == PageCloseButtonType.closeWhite) {
      backPic = 'assets/images/page_close.png';
    } else if (backButtonType == PageCloseButtonType.closeBlack) {
      backPic = 'assets/images/page_close_black.png';
    } else if (backButtonType == PageCloseButtonType.arrowWhite) {
      backPic = 'assets/images/nav_arrow_white.png';
    }
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        if (callBack != null) {
          callBack?.call();
        } else {
          NavigatorUtil.unFocus();
          RouterUtil.maybePop(
            context,
          );
        }
      },
      child: Padding(
        padding: const EdgeInsets.all(10),
        child: Image.asset(
          backPic,
          width: 22,
          height: 22,
        ),
      ),
    );
  }
}

class JDAppBar extends StatelessWidget implements PreferredSizeWidget {
  final Widget? leftWidget;
  final bool showBackButton;
  final bool? enableDividerLine;
  final bool safeAreaTop;
  final ValueNotifier<String> titleNotifier;
  // 中间自定义视图
  final ValueNotifier<Widget>? titleWidgetNotifier;
  final TextStyle? textStyle;
  final Color? backgroundColor;
  final List<Widget>? actionWidgets;
  final Widget? backgroundWidget;

  /// 返回上一层时携带的额外请求参数,null代表没有额外参数
  final PopExtraParams? popExtraParams;
  // 返回按钮是不是叉号
  final PageCloseButtonType backButtonType;
  JDAppBar({
    Key? key,
    String? title,
    ValueNotifier<String>? titleNotifier,
    this.leftWidget,
    this.textStyle,
    this.titleWidgetNotifier,
    this.backgroundColor,
    this.backgroundWidget,
    this.actionWidgets,
    this.popExtraParams,
    this.safeAreaTop = true,
    this.showBackButton = true,
    this.backButtonType = PageCloseButtonType.arrowBlack,
    this.enableDividerLine,
  })  : titleNotifier = titleNotifier ?? ValueNotifier<String>(title ?? ''),
        super(key: key);

  @override
  Size get preferredSize => Size(JDDevice.width, kPreferredHeight);

  @override
  Widget build(BuildContext context) {
    String backPic = 'assets/images/nav_arrow_white.png';
    if (backButtonType == PageCloseButtonType.closeWhite) {
      backPic = 'assets/images/page_close.png';
    } else if (backButtonType == PageCloseButtonType.closeBlack) {
      backPic = 'assets/images/page_close_black.png';
    } else if (backButtonType == PageCloseButtonType.arrowWhite) {
      backPic = 'assets/images/nav_arrow_white.png';
    } else if (backButtonType == PageCloseButtonType.arrowBlack) {
      backPic = 'assets/images/back.png';
    }
    final Widget backButton = Padding(
      padding: const EdgeInsets.fromLTRB(15, 10, 10, 10),
      child: Image.asset(
        backPic,
        width: 22, height: 22,
        // color: Colors.black,
      ),
    );

    Widget contentWidget = Stack(children: [
      backgroundWidget ?? Gap.empty,
      Padding(
        padding:
            EdgeInsets.only(top: safeAreaTop ? 0 : JDDevice.statusBarHeight),
        child: Row(children: [
          Visibility(
            visible: showBackButton,
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                NavigatorUtil.unFocus();
                RouterUtil.maybePop(context, popExtraParams?.call());
              },
              // onLongPress: () =>
              //     TDRouterUtil.pop(context, popExtraParams?.call()),
              child: SizedBox(
                width: kPreferredHeight,
                height: kPreferredHeight,
                child: Center(child: backButton),
              ),
            ),
          ),
          Visibility(
              visible: leftWidget != null, child: leftWidget ?? Gap.empty),
          const Spacer(),
          ...?actionWidgets,
          SizedBox(width: 12, height: kPreferredHeight),
        ]),
      ),
      Padding(
        padding:
            EdgeInsets.only(top: safeAreaTop ? 0 : JDDevice.statusBarHeight),
        child: Container(
          alignment: Alignment.center,
          height: kPreferredHeight,
          // margin: EdgeInsets.symmetric(horizontal: kPreferredHeight + 4.dp),
          child: titleWidgetNotifier != null
              ? ValueListenableBuilder(
                  valueListenable: titleWidgetNotifier!,
                  builder: (BuildContext context, Widget value, Widget? child) {
                    return value;
                  })
              : ValueListenableBuilder(
                  valueListenable: titleNotifier,
                  builder: (BuildContext context, String value, Widget? child) {
                    return Text(
                      value,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: textStyle ??
                          const TextStyle(
                              color: Colors.white,
                              fontSize: 17,
                              fontWeight: FontWeight.w600),
                    );
                  },
                ),
        ),
      ),
    ]);

    if (safeAreaTop == true) {
      contentWidget = SafeArea(top: true, child: contentWidget);
    }
    return Container(
      width: JDDevice.width,
      decoration: BoxDecoration(
        boxShadow: () {
          if (enableDividerLine == null) return null;
          if (enableDividerLine == false) return null;
          if (backgroundColor?.alpha == 0) return null;
          return [
            BoxShadow(
                color: const Color(0x0A000000),
                blurStyle: BlurStyle.solid,
                offset: Offset(0, 0.5.dp))
          ];
        }(),
        color: backgroundColor ?? Colors.blue.withOpacity(0.9),
      ),
      child: contentWidget,
    );
  }
}

class TDWidgetAppBar extends StatelessWidget implements PreferredSizeWidget {
  final Widget child;
  final Color? color;
  final bool safeAreaTop;
  final Alignment? alignment;
  final EdgeInsets? padding;
  final EdgeInsets? margin;

  const TDWidgetAppBar({
    super.key,
    required this.child,
    this.color,
    this.safeAreaTop = true,
    this.alignment,
    this.padding = const EdgeInsets.symmetric(horizontal: 15.0),
    this.margin,
  });

  @override
  Size get preferredSize => Size(double.infinity, kPreferredHeight);

  @override
  Widget build(BuildContext context) {
    Widget child = Container(
      alignment: alignment,
      padding: padding,
      margin: margin,
      height: kPreferredHeight,
      child: this.child,
    );
    if (safeAreaTop == true) {
      child = SafeArea(top: true, child: child);
    }
    if (color != null) {
      child = DecoratedBox(
        decoration: BoxDecoration(color: color),
        child: child,
      );
    }
    return child;
  }
}

class TDBaseSliverPersistentHeader extends SliverPersistentHeaderDelegate {
  Widget child;
  double height;

  TDBaseSliverPersistentHeader({required this.child, required this.height});

  @override
  Widget build(
          BuildContext context, double shrinkOffset, bool overlapsContent) =>
      Container(
        color: Colors.white,
        child: child,
      );

  @override
  double get maxExtent => height;

  @override
  double get minExtent => height;

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) =>
      false;
}
